package org.yxj.customlibrary;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.yxjme.stateviewlayoutlibrary.StateViewLayout;
import org.yxj.customlibrary.util.CustomConstantUtil;
import org.yxj.customlibrary.util.LogUtil;
import org.yxj.customlibrary.util.Utils;
import org.yxj.customlibrary.v.AddCustomMainHeadView;
import org.yxj.customlibrary.v.AddCustomTextPop;
import org.yxj.customlibrary.v.CustomTextBean;
import org.yxj.customlibrary.v.CustomTextView;
import org.yxj.customlibrary.v.EditCustomTextView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

public class CustomMetalBarActivity extends AppCompatActivity {

    public ImageView imRes ;
    public TextView btn_delete;
    public EditCustomTextView mEditCustomTextView;
    public AddCustomMainHeadView mAddCustomMainHeadView;
    public int[] locationOnScreen = new int[2];
    private HashMap<CustomTextView, CustomTextBean> hashMap = new HashMap<>();


    private View lay_content ;
    private StateViewLayout mStateViewLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.stateBarColor(this, 0);
        setContentView(R.layout.activity_custom_metal_bar);
        initView();
        init();
    }



    private int[] resSize = new int[2];

    private void init() {
        Bundle b = getIntent().getBundleExtra(CustomConstantUtil.Data);
        mStateViewLayout.setMode(StateViewLayout.LOADING);
        if (b!=null){
            String imgUrl= b.getString(CustomConstantUtil.CustomImRes);
            Glide.with(this)
                    .load(imgUrl)
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            Bitmap bitmap =  measureBitSize(resource) ;
                            imRes.setImageBitmap(bitmap);
                            resSize[0] = bitmap.getWidth() ;
                            resSize[1] = bitmap.getHeight();
                            lay_content.setVisibility(View.VISIBLE);
                            mStateViewLayout.setMode(StateViewLayout.NONE);
                        }
                    });
        }else {
            lay_content.setVisibility(View.GONE);
            mStateViewLayout.setMode(StateViewLayout.NO_DATA);
        }
    }


    /**
     * 图片适配机器屏幕
     */
    public Bitmap measureBitSize(Bitmap resource){
        int bw = resource.getWidth();
        int bh = resource.getHeight();

        int w = getResources().getDisplayMetrics().widthPixels ;
        int h = getResources().getDisplayMetrics().heightPixels ;

        float scale = 0 ;

        if (bw < w && bh < h){
            scale  = (float) Math.min(w * 1.0 / bw , h * 1.0 / bh);
        }


        if (bw > w && bh < h){
            scale  = (float) (w * 1.0 / bw);
        }


        if (bw < w && bh > h){
            scale  = (float) (h * 1.0 / bh);
        }

        if (bw > w && bh > h){
            scale  = (float) Math.max(w * 1.0 / bw , h * 1.0 / bh);
        }

        Matrix matrix = new Matrix();
        matrix.postScale(scale,scale);
        Bitmap bitmap = Bitmap.createBitmap(resource,0,0,bw,bh,matrix,false);

        return bitmap;
    }




    private void initView() {
        mStateViewLayout = findViewById(R.id.mStateViewLayout);
        lay_content = findViewById(R.id.lay_content);
        imRes = findViewById(R.id.imRes);
        btn_delete = findViewById(R.id.btn_delete);
        mEditCustomTextView = findViewById(R.id.mEditCustomTextView);
        mAddCustomMainHeadView = findViewById(R.id.mAddCustomMainHeadView);
        mAddCustomMainHeadView.setAddCustomTextHeadListener(addCustomTextHeadListener);
        findViewById(R.id.btn_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishTask();
            }
        });
    }



    private AddCustomMainHeadView.AddCustomTextHeadListener addCustomTextHeadListener = new AddCustomMainHeadView.AddCustomTextHeadListener(){

        @Override
        public void onBack() {
            finish();
        }

        @Override
        public void onAdd() {
            AddCustomTextTask();
        }
    };



    /**
     * 完成编辑
     */
    private void finishTask() {
        Bitmap bitmap = Bitmap.createBitmap(mEditCustomTextView.getWidth(), mEditCustomTextView.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        mEditCustomTextView.draw(canvas);
        LogUtil.LOG_V("[finishTask]->","view -> Width = "+bitmap.getWidth()+",Height = "+bitmap.getHeight());
        LogUtil.LOG_V("[finishTask]->","bit -> Width = "+resSize[0]+",Height = "+resSize[1]);


        Bitmap res = Bitmap.createBitmap(bitmap, 0, (bitmap.getHeight() - resSize[1])/2, resSize[0], resSize[1]);
        saveBitmapToCard(this,res);
    }





    /**
     * 保存
     *
     *
     * @param activity
     * @param b
     */
    public static Uri saveBitmapToCard(final Activity activity, final Bitmap b){
        FileOutputStream outputStream = null;
        try {
            File f=new File(Environment.getExternalStorageDirectory().getPath());

            File file = new File(f.getPath()+File.separator+System.currentTimeMillis()+".png");
            file.createNewFile();
            outputStream = new FileOutputStream(file.getPath());
            b.compress(Bitmap.CompressFormat.PNG,100,outputStream);

            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");

            Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            return uri;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null ;
    }





    /**
     * 添加定制文字
     */
    private void AddCustomTextTask() {
        new AddCustomTextPop(CustomMetalBarActivity.this)
                .setCustomBg(mEditCustomTextView)
                .setAddCustomTextResultListener(new AddCustomTextPop.AddCustomTextResultListener() {
                    @Override
                    public void onResult(String text, int color,Typeface typeface) {
                        CustomTextView customTextView = new CustomTextView(CustomMetalBarActivity.this);
                        customTextView.setText(text)
                                .setTextColor(color)
                                .setTypeFace(typeface)
                                .setItemCustomListener(new MyItemCustomListener());

                        mEditCustomTextView.addView(customTextView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));

                        CustomTextBean customTextBean = new CustomTextBean();
                        customTextBean.customTextView = customTextView;
                        customTextBean.customText = text;
                        customTextBean.typeface = typeface ;
                        customTextBean.customTextColor = color;
                        hashMap.put(customTextView, customTextBean);
                    }
                }).show(CustomMetalBarActivity.this);
    }





    public class MyItemCustomListener implements CustomTextView.ItemCustomListener {

        @Override
        public void onDrag(MotionEvent event, boolean isDragging, CustomTextView customTextView) {
            btn_delete.getLocationOnScreen(locationOnScreen);
            btn_delete.setVisibility(isDragging ? View.VISIBLE : View.GONE);

            float x = event.getRawX();
            float y = event.getRawY();

            if (x >= locationOnScreen[0]
                    && x <= locationOnScreen[0] + btn_delete.getMeasuredWidth()
                    && y >= locationOnScreen[1]
                    && y <= locationOnScreen[1] + btn_delete.getMeasuredHeight()) {
                btn_delete.setBackgroundResource(R.drawable.checked_delete_bg);
                btn_delete.setText("松开删除");
                if (!isDragging) {
                    mEditCustomTextView.removeView(customTextView);
                    hashMap.remove(customTextView);
                }
            } else {
                btn_delete.setBackgroundResource(R.drawable.default_delete_bg);
                btn_delete.setText("拖到此处删除");
            }
        }


        @Override
        public void onClick(final CustomTextView customTextView) {
            LogUtil.LOG_V("[StopDrag]->onClick");

            Typeface f = Typeface.createFromAsset(getAssets(), "zh_4.ttf");
            customTextView.setTypeFace(f);

            CustomTextBean customText = hashMap.get(customTextView);
            new AddCustomTextPop(CustomMetalBarActivity.this)
                    .setCustomBg(mEditCustomTextView)
                    .setTypeface(customText.typeface)
                    .setText(customText.customText)
                    .setTextColor(customText.customTextColor)
                    .setAddCustomTextResultListener(new AddCustomTextPop.AddCustomTextResultListener() {
                        @Override
                        public void onResult(String text, int color,Typeface typeface) {
                            CustomTextBean customTextBean = hashMap.get(customTextView);
                            customTextBean.customText = text;
                            customTextBean.customTextColor = color;
                            customTextBean.typeface = typeface ;

                            customTextView.setText(text);
                            customTextView.setTypeFace(typeface) ;
                            customTextView.setTextColor(color);
                            hashMap.put(customTextView, customTextBean);
                        }
                    }).show(CustomMetalBarActivity.this);
        }
    }
}